//
//  WURLRequset.m
//  OneArticle
//
//  Created by mac on 14/12/18.
//  Copyright (c) 2014年 AliliWl. All rights reserved.
//

#import "WURLRequset.h"

@implementation WURLRequset
@synthesize finishCallbackBlock,resultData;
/**
 *  同步get
 */
+ (void)getSynchronizationWithURLString:(NSString *)URLString FinishCallBack:(getDictionaryCallbackBlock)callback
{
    //第一步，创建URL
    NSURL *url = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //第二步，通过URL创建网络请求
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSError *error;
    //第三步，连接服务器
    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (error == nil) {
        callback(YES,[self dataToDictionary:receivedData]);
    }
    else
    {
        callback(NO,nil);
    }
}
/**
 *  同步post
 */
+ (void)postSynchronizationWithURLString:(NSString *)URLString Paramters:(NSString *)params FinishCallBack:(getDictionaryCallbackBlock)callback{
    //第一步，创建URL
    NSURL *URL = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //第二步，通过URL创建网络请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSError *error;
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (error == nil) {
        callback(YES,[self dataToDictionary:receivedData]);
    }else{
        callback(NO,nil);
    }
}
/**
 *  将Data数据类型转成Dictionary
 *
 *  @param data 需要转成Dictionary的数据源
 *
 *  @return 返回Dictionary的数据源
 */
+ (NSDictionary *) dataToDictionary:(NSData *) data
{
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
- (NSDictionary *) dataToDictionary:(NSData *) data
{
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
/**
 *  异步POST
 */
+ (void)postExecuteWithUrlStr:(NSString *)urlStr Paramters:(NSString *)params FinishCallback:(getDictionaryCallbackBlock)callback
{
    // 生成一个post请求回调委托对象（实现了<NSURLConnectionDataDelegate>协议）
    WURLRequset *executorDelegate = [[WURLRequset alloc] init];
    executorDelegate.finishCallbackBlock = callback; // 绑定执行完成时的block
    NSURL *url = [NSURL URLWithString:urlStr]; // 生成NSURL对象
    // 生成Request请求对象（并设置它的缓存协议、网络请求超时配置）
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"]; // 设置为post请求
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; // 设置请求参数
    // 执行请求连接
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:executorDelegate];
    NSLog(conn ? @"连接创建成功" : @"连接创建失败");
}
/**
 *  异步get
 */
+ (void)getExecuteWithUrlStr:(NSString *)urlStr FinishCallback:(getDictionaryCallbackBlock)callback{
    // 生成一个post请求回调委托对象（实现了<NSURLConnectionDataDelegate>协议）
    WURLRequset *executorDelegate = [[WURLRequset alloc] init];
    executorDelegate.finishCallbackBlock = callback; // 绑定执行完成时的block
    //第一步,创建URL请求
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //第二步，创建请求
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    //第三步，连接服务器
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:executorDelegate];
    NSLog(connection ? @"连接创建成功" : @"连接创建失败");
}
/**
 * 接收到服务器回应的时回调
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 初始化NSMutableData对象（用于保存执行结果）
    if(!resultData){
        resultData = [[NSMutableData alloc] init];
    }else{
        [resultData setLength:0];
    }
}
/**
 * 接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [resultData appendData:data]; // 追加结果
}
/**
 * 数据传完之后调用此方法
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 把请求结果以UTF-8编码转换成字符串
    if (finishCallbackBlock) { // 如果设置了回调的block，直接调用
        finishCallbackBlock(YES,[self dataToDictionary:resultData]);
    }
}
/**
 * 网络请求过程中，出现任何错误（断网，连接超时等）会进入此方法
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"network error: %@", [error localizedDescription]);
    if (finishCallbackBlock) { // 如果设置了回调的block，直接调用
        finishCallbackBlock(NO,nil);
    }
    
}
@end
